<template>
  <div class="container mx-auto py-8">
    <div class="flex gap-8">
      <!-- 左侧品牌列表 -->
      <div class="w-1/5 bg-white rounded-lg shadow-md p-4" v-loading="loading1">
        <h2 class="text-xl font-bold mb-4">Brand List</h2>
        <ul class="space-y-2" >
          <li 
            v-for="brand in brands" 
            :key="brand.MFGID"
            class="px-4 py-2 rounded-md cursor-pointer transition-colors"
            :class="{
              'bg-primary text-white': currentBrand?.MFGID === brand.MFGID,
              'hover:bg-gray-100': currentBrand?.MFGID !== brand.MFGID
            }"
            @mouseenter="handleBrandChange(brand)"
          >
            {{ brand.MfgName }}
          </li>
        </ul>
      </div>

      <!-- 中间型号列表 -->
      <div class="w-2/5 bg-white rounded-lg shadow-md p-4" v-loading="loading2">
        <h2 class="text-xl font-bold mb-4">
          {{ currentBrand ? `${currentBrand.MfgName} Product Model` : 'Please select brand' }}
        </h2>
        
        <div v-if="currentBrand" class="">
          <div 
            v-for="model in currentPageModels" 
            :key="model.ParentID"
            class="px-4 py-2 rounded-lg hover:shadow-md transition-shadow cursor-pointer"
            @mouseenter="handleSelectModel(model)"
            :class="{
              'bg-primary text-white': currentModel?.ParentID === model.ParentID,
              'hover:bg-gray-100': currentModel?.ParentID !== model.ParentID
            }"
          >
            {{ model.ParentName }}
          </div>
          <!-- 分页器 -->
          <div class="flex justify-center mt-2" v-if="totalPages >= 1 && parentCategories">
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :total="parentCategories.length"
              layout="prev, pager, next"
              @current-change="handlePageChange"
            />
          </div>
        </div>
         
        <div 
          v-else 
          class="flex items-center justify-center h-64 text-gray-500"
        >
          Please select the brand on the left to view the product model
        </div>
      </div>

      <!-- 右侧型号列表 -->
      <div class="w-2/5 bg-white rounded-lg shadow-md p-4" v-loading="loading3">
        <h2 class="text-xl font-bold mb-4">
          {{ currentModel ? `${currentModel.ParentName} Product Model` : 'Please select brand' }}
        </h2>
        <div v-if="currentModel" class="">
          
          <div 
            v-for="model in childrenModels" 
            :key="model.CategoryID"
            class="px-4 py-2 rounded-lg hover:shadow-md transition-shadow cursor-pointer hovertype"
            @click="handleSelectDetail(model)"
          >
            {{ model.CategoryName }}
          </div>

          <!-- 分页器 -->
          <div class="flex justify-center mt-2" v-if="totalPages2 >= 1 && currentModel">
            <el-pagination
              v-model:current-page="currentPage2"
              :page-size="pageSize2"
              :total="categories.length"
              layout="prev, pager, next"
              @current-change="handlePageChange2"
            />
          </div>
        </div>
         
        <div 
          v-else 
          class="flex items-center justify-center h-64 text-gray-500"
        >
          Please select the brand on the left to view the product model
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useNuxtApp } from '#app'
const { $request } = useNuxtApp() // 获取 Axios 实例
// import brands from './data/brand.js'
import { useBrandStore } from '~/store/brandStore'
const brand = useBrandStore()
const router = useRouter()
interface Model {
  id: number
  name: string
}

interface Brand {
  MFGID: number
  MfgName: string
}

const loading1 = ref(false)
const loading2 = ref(false)
const loading3 = ref(false)
// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
// 分页相关
const currentPage2 = ref(1)
const pageSize2 = ref(20)

const currentBrand = ref<Brand | null>(null) // 当前选择的品牌
const currentModel = ref<Model | null>(null) // 当前选择的型号
const currentDetail = ref<Model | null>(null) // 当前选择的型号

const brands = ref<Brand[]>([])
const parentCategories = ref([])
const categories = ref([])


// 计算当前页的数据
const currentPageModels = computed(() => {
  if (!currentBrand.value.MfgCategorysDtos) return []
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return currentBrand.value.MfgCategorysDtos.slice(start, end)
})

// 计算子集页数据
const childrenModels = computed(() => {
  if (!currentModel.value.Info_MfgCategorys) return []
  const start = (currentPage2.value - 1) * pageSize.value
  const end = start + pageSize.value
  return currentModel.value.Info_MfgCategorys.slice(start, end)
})


// 计算总页数
const totalPages = computed(() => {
  if (!parentCategories.value) return 0
  return Math.ceil(parentCategories.value.length / pageSize.value)
})
// 计算总页数
const totalPages2 = computed(() => {
  if (!categories.value) return 0
  return Math.ceil(categories.value.length / pageSize2.value)
})

// 切换品牌时重置页码
const handleBrandChange = (brand: Brand) => {
  currentBrand.value = brand
  currentPage.value = 1
}

const handleSelectModel = (model :Model) => {
  currentModel.value = model
  currentPage2.value = 1
}

const handleSelectDetail = (model) => {
  // 获取该id的模型并跳转
  // window.open(`/detail?Category=${model.Category}`, '_blank')
  router.push(`/product?Brand=${currentBrand.value.MFGID}&Parent=${currentModel.value.ParentID}&Category=${model.CategoryID}`)
}

const handleEnterDetail = (model) => {
  currentDetail.value = model
  console.log('currentDetail:', currentDetail.value);
  
}

// 页码改变处理
const handlePageChange = (page: number) => {
  currentPage.value = page
}

// 页码改变处理
const handlePageChange2 = (page: number) => {
  currentPage2.value = page
}


// 获取品牌列表的接口
const fetchManufacturers = async () => {
  loading1.value = true
  // 查看pinia中的brand中是否已经存在数据
  if (brand.brands.length) {
    brands.value = brand.brands
    loading1.value = false
    return
  }
  brand.fetchBrand().then(() => {
    brands.value = brand.brands
    loading1.value = false
  })
}


onMounted(async () => {
  fetchManufacturers()
})


</script>


<style scoped>
.hovertype:hover {
  background-color:  rgb(24, 144, 255);
  color: #fff;
  cursor: pointer;
}
</style>